<?php

namespace app\admin\controller\shopro\user;

use think\Db;
use app\admin\controller\shopro\Common;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\user\Coupon as UserCouponModel;

class User extends Common
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new UserModel;
    }

    /**
     * 用户列表
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $data = $this->model->sheepFilter()->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $data);
    }

    /**
     * 用户详情
     *
     * @param  $id
     */
    public function detail($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $user = $this->model->with(['third_oauth', 'parent_user','father_user'])->where('id', $id)->find();
        if (!$user) {
            $this->error(__('No Results were found'));
        }

        $this->success('获取成功', null, $user);
    }

    /**
     * 更新用户
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit($id = null)
    {
        $params = $this->request->only(['username', 'nickname', 'mobile', 'password', 'avatar', 'gender', 'email', 'status','integral_release']);

        if (empty($params['password'])) unset($params['password']);
        if (empty($params['username'])) unset($params['username']);

        $params['id'] = $id;
        $this->svalidate($params, '.edit');
        unset($params['id']);

        $user = $this->model->where('id', $id)->find();
        $user->save($params);

        $this->success('更新成功', null, $user);
    }

    /**
     * 删除用户(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if (empty($id)) {
            $this->error(__('Parameter %s can not be empty', 'id'));
        }

        $id = explode(',', $id);
        $list = $this->model->where('id', 'in', $id)->select();
        $result = Db::transaction(function () use ($list) {
            $count = 0;
            foreach ($list as $item) {
                $count += $item->delete();
            }

            return $count;
        });

        if ($result) {
            $this->success('删除成功', null, $result);
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    public function recharge()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $params = $this->request->only(['id', 'type', 'amount', 'memo']);
        if (!in_array($params['type'], ['money','greenscore', 'score','integral','commission'])) {
            error_stop('参数错误');
        }

        $result = Db::transaction(function () use ($params) {
            return WalletService::change($params['id'], $params['type'], $params['amount'], 'admin_recharge', [], $params['memo']);
        });
        if ($result) {
            $this->success('充值成功');
        }
        $this->error('充值失败');
    }


    /**
     * 用户优惠券列表
     */
    public function coupon($id)
    {
        $userCoupons = UserCouponModel::sheepFilter()->with('coupon')->where('user_id', $id)
            ->order('id', 'desc')->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $userCoupons);
    }

    /*
 * 导出
 * */
    public function exportDelivery()
    {
        $cellTitles = [
            // 订单表字段
            'id' => 'Id',
            'username' => '用户名',
            'mobile' => '手机号',
            'commission' => '佣金',
            'total_consume' => '总消费',
            'score' => '积分',
            'money' => '余额',
            'greenscore' => '绿色积分',
            'createtime' => '注册时间',
        ];

        // 数据总条数
        $total = $this->model->sheepFilter()->count();      // nosend 加了 noApplyRefund
        if ($total <= 0) {
            $this->error('导出数据为空');
        }

        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '用户列表',
            'cell_titles' => $cellTitles,
            'total' => $total,
            'is_sub_cell' => false,
            'sub_start_cell' => '',
            'sub_field' => ''
        ];

        $result = $export->export($params, function ($pages) use (&$total) {
            // 未申请全额退款的
            $datas = $this->model->sheepFilter()
                ->limit((($pages['page'] - 1) * $pages['list_rows']), $pages['list_rows'])
                ->select();

            $datas = collection($datas)->toArray();

            $newDatas = [];
            foreach ($datas as &$order) {
         /*       $withdraw_type = $this->model->getWithdrawTypeTextAttr($order['withdraw_type'],$order);
                if($order['status']==-1){
                    $status='已拒绝';
                }elseif ($order['status']==0){
                    $status='待审核';
                }elseif ($order['status']==1){
                    $status='处理中';
                }elseif ($order['status']==2){
                    $status='已处理';
                }*/
                $data = [
                    'id' => $order['id'],
                //    'user_id' => db::name('user')->where('id',$order['user_id'])->value('mobile'),
                    //  'user_id' => $order['user_id'],
                    'username' => $order['username'],
                    'mobile' => $order['mobile'],
                    'commission' => $order['commission'],
                    'total_consume' => $order['total_consume'],
                    'score' => $order['score'],
                    'money' => $order['money'],
                    'greenscore' => $order['greenscore'],
                    'createtime' => $order['createtime'],
                ];
                $newDatas[] = $data;
            };

            if ($pages['is_last_page']) {
                $newDatas[] = ['order_id' => "总数：" . $total . "；"];
            }
            return $newDatas;
        });
        $this->success('导出成功' . (isset($result['file_path']) && $result['file_path'] ? '，请在服务器: “' . $result['file_path'] . '” 查看' : ''), null, $result);
    }
}
